package com.xbongbong.pro.bi.commons.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.xbongbong.paas.constant.FieldAttrConstant;
import com.xbongbong.paas.constant.XbbConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.enums.AggTypeEnum;
import com.xbongbong.paas.enums.BIProductReformEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.bi.XbbTableRefEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.bi.commons.pojo.ParamPojo;
import com.xbongbong.pro.bi.commons.pojo.vo.GroupSqlVO;
import com.xbongbong.pro.bi.commons.sql.SqlBuilderHandler;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.enums.IntervalTypeEnum;
import com.xbongbong.pro.enums.errorcodes.BiErrorCodeEnum;
import com.xbongbong.pro.service.toolbox.statistic.help.BIHelp;
import com.xbongbong.pro.statistic.constant.RelatedProductConstant;
import com.xbongbong.pro.statistic.enums.ChartTypeEnum;
import com.xbongbong.pro.statistic.pojo.ChartFieldAttrPojo;
import com.xbongbong.pro.statistic.pojo.SlaveSourcePojo;
import com.xbongbong.pro.statistic.result.pojo.FieldAttrPojo;
import com.xbongbong.pro.statistics.help.CommonHelper;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ext.WorkOrderExplainEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractPerformanceEnum;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author gzt
 * @version 1.0
 * @Description -
 * @datetime - 2022/6/15-13:57
 * @since v1.0
 */
@Component
@Slf4j
public class SrSelectItemHandler {

    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private SrTeamJoinHandler srTeamJoinHandler;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;


    public List<ChartFieldAttrPojo> getExplainEntityList(String corpId, Set<String> fieldCheckSet, ParamPojo paramPojo) throws XbbException {
        Integer businessType = paramPojo.getBusinessType();
        Map<String, FieldAttrEntity> explainMap = null;
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
            //工单
            //解释表信息
            WorkOrderExplainEntityExt workOrderExplainEntityExt = workOrderExplainModel.getByFormId(paramPojo.getFormId(), corpId);
            if (workOrderExplainEntityExt == null) {
                throw new XbbException(BiErrorCodeEnum.API_ERROR_241042);
            }
            explainMap = ExplainUtil.getExplainMap(workOrderExplainEntityExt.getExplains());
        } else {
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(paramPojo.getFormId(), corpId);
            if (paasFormExplainEntity != null) {
                explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains());
            }
        }
        //explains里面没有id或者dataId
        //List<ChartFieldAttrPojo> fieldAttrEntities = fieldCheckSet.stream().filter(field->!StringUtils.equals(field,FieldTypeEnum.ID.getAlias()) && !StringUtils.equals(field,FieldTypeEnum.DATAID.getAlias())).map(field -> {
        Map<String, FieldAttrEntity> finalExplainMap = explainMap;
        List<ChartFieldAttrPojo> fieldAttrEntities = fieldCheckSet.stream().filter(field -> !StringUtils.equals(field, FieldTypeEnum.DATAID.getAlias())).map(field -> {
            ChartFieldAttrPojo chartFieldAttrPojo = new ChartFieldAttrPojo();
            FieldAttrEntity fieldAttrEntity = null;
            if (finalExplainMap != null) {
                fieldAttrEntity = finalExplainMap.get(field);
            }
                //if (fieldAttrEntity == null && StringUtils.equals(field,FieldTypeEnum.ID.getAlias())) {
                /*if (fieldAttrEntity == null) {
                    fieldAttrEntity = new ChartFieldAttrPojo();
                    BIProductReformEnum biProductReformEnum = BIProductReformEnum.getEnumByProductBusinessType(businessType);
                    if (Objects.nonNull(biProductReformEnum)) {
                        if (Objects.equals(RelatedProductConstant.COMMON_PRODUCT_SERIAL_NO_ATTR, field)) {
                            //fieldAttrEntity.setOriginalAttr(RelatedProductConstant.COMMON_PRODUCT_SERIAL_NO_ATTR);
                            //fieldAttrEntity.setAttr(ProductEnum.PRODUCT_NO.getAttr());
                        } else {
                            fieldAttrEntity.setAttr(StringUtil.getDataBaseString(field));
                            fieldAttrEntity.setOriginalAttr(StringUtil.getDataBaseString(field));
                        }
                    }
                }*/
            //if (fieldAttrEntity == null && StringUtils.equals(field,FieldTypeEnum.ID.getAlias())) {
            String dataBaseString = StringUtil.getDataBaseString(field);
            if (fieldAttrEntity == null) {
                fieldAttrEntity = new ChartFieldAttrPojo();
                BIProductReformEnum biProductReformEnum = BIProductReformEnum.getEnumByProductBusinessType(businessType);
                if (Objects.nonNull(biProductReformEnum)) {
                    if (Objects.equals(RelatedProductConstant.COMMON_PRODUCT_SERIAL_NO_ATTR, field)) {
                        //fieldAttrEntity.setOriginalAttr(RelatedProductConstant.COMMON_PRODUCT_SERIAL_NO_ATTR);
                        //fieldAttrEntity.setAttr(ProductEnum.PRODUCT_NO.getAttr());
                    } else {
                        fieldAttrEntity.setAttr(dataBaseString);
                        fieldAttrEntity.setOriginalAttr(dataBaseString);
                    }
                }
                //formid explian 里没有
                if(Objects.equals(FieldTypeEnum.FORM_ID.getAlias(),field)){
                    fieldAttrEntity.setAttr(FieldTypeEnum.FORM_ID.getAlias());
                    fieldAttrEntity.setFieldType(FieldTypeEnum.FORM_ID.getType());
                    fieldAttrEntity.setAttrName(FieldTypeEnum.FORM_ID.getDescription());
                }
            }
            fieldAttrEntity.setFormId(paramPojo.getFormId());
            fieldAttrEntity.setSaasMark(paramPojo.getSaasMark());
            fieldAttrEntity.setBusinessType(businessType);
            if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT_PERFORMANCE.getCode())) {
                if (!Objects.equals(StringConstant.ID, field)) {
                    fieldAttrEntity.setAttr(dataBaseString);
                }
            }
            BeanUtil.copyProperties(fieldAttrEntity, chartFieldAttrPojo);

            return chartFieldAttrPojo;
        }).collect(Collectors.toList());

        return fieldAttrEntities;
    }

    /**
     * 查询表的自定义展现数据
     *
     * @param fieldAttrPojoList
     * @param summaryAttrList
     * @param tableHead
     * @param parseAttrMap
     * @param summaryAttrMap
     * @param chartEntity
     * @throws XbbException
     */
    public Pair<List<String>, HashMap<String, Set<String>>> displayAttrAssemble(List<ChartFieldAttrPojo> fieldAttrPojoList, List<FieldAttrEntity> summaryAttrList
            , JSONArray tableHead,
                Map<JSONObject, FieldAttrEntity> parseAttrMap, Map<String, FieldAttrPojo> summaryAttrMap,
                ChartEntity chartEntity, boolean isSingle,
                Map<String, String> sortMap,Map<Long, String> formIdTableMap) throws XbbException {
        List<String> fieldsList = new ArrayList<>();
        JSONObject formIdAttr = null;
        if (chartEntity != null) {
            formIdAttr = chartEntity.getFormIdAttr();
            formIdTableMap = new CommonHelper().getFormIdTableMap(chartEntity, isSingle);
        }
        HashMap<String, Set<String>> selectItemsMap = Maps.newHashMap();
        //查询表若只选择负责人/协同人时 需要取到对应的dataId 作为查询条件
        if (isSingle) {
            if (CollectionsUtil.isNotEmpty(fieldAttrPojoList)) {
                ChartFieldAttrPojo chartFieldAttrPojo = fieldAttrPojoList.get(0);
                if (Objects.nonNull(chartFieldAttrPojo)){
                    Long formId = chartFieldAttrPojo.getFormId();
                    BIProductReformEnum biProductReformEnum = BIProductReformEnum.getEnumByProductBusinessType(chartFieldAttrPojo.getBusinessType());
                    if (Objects.isNull(biProductReformEnum)) {
                        fieldsList.add(String.format("%s%s%s", formIdTableMap.get(formId)+XbbConstant.POINT+FieldTypeEnum.ID.getAlias(), XbbConstant.AS, FieldTypeEnum.ID.getAlias()));
                    }
                    addSelectCol(formIdTableMap, selectItemsMap, formId, FieldTypeEnum.ID.getAlias());
                }
            }
        } else {
            for (Map.Entry<String, Object> entry : formIdAttr.entrySet()) {
                String formId = entry.getKey();
                Object value = entry.getValue();
                JSONObject valueObj = new JSONObject((Map<String, Object>) value);
                String alais = valueObj.getString(StringConstant.DATA_ID);
                fieldsList.add(String.format("%s.id AS %s", formIdTableMap.get(Long.valueOf(formId)), alais));
                //addSelectCol(formIdTableMap, selectItemsMap, Long.parseLong(formIdSuff), FieldTypeEnum.ID.getAlias());
            }
        }
        if (CollectionsUtil.isNotEmpty(fieldAttrPojoList)) {
            for (ChartFieldAttrPojo fieldAttrPojo : fieldAttrPojoList) {
                String attr = fieldAttrPojo.getAttr();
                if (Objects.isNull(attr)) {//数据集预览子表单特殊处理
                    continue;
                }
                //老BI逻辑兼容
                //Long formId = fieldAttrPojo.getFormId();
                //处理headName
                boolean specialFlag = handleHeadName(chartEntity, isSingle, fieldsList, formIdTableMap, fieldAttrPojo, tableHead, parseAttrMap,selectItemsMap);
                //上面加过的后面就不用再添加
                if (specialFlag) {
                    continue;
                }

                addFieldaliasList(selectItemsMap, isSingle, fieldsList, null, formIdTableMap, fieldAttrPojo, attr, sortMap, chartEntity);
                Long formId = fieldAttrPojo.getFormId();
                if (Objects.equals(fieldAttrPojo.getFieldType(), FieldTypeEnum.LINK_BUSINESS_SINGLE.getType()) || Objects.equals(fieldAttrPojo.getFieldType(), FieldTypeEnum.LINK_BUSINESS_MULTI.getType())
                        || Objects.equals(fieldAttrPojo.getFieldType(), FieldTypeEnum.LINK_RECEIVER.getType())) {
                    attr = fieldAttrPojo.getLinkedText();
                    JSONObject linkedJsonObject = fieldAttrPojo.getLinkedAttr();
                    if(linkedJsonObject!=null){
                        if (EsUtil.setInData(linkedJsonObject.getInteger(FieldAttrConstant.FIELD_TYPE))) {
                            /*String jsonExtract = JSON_EXTRACT;
                            if (Objects.equals(FieldTypeEnum.NUM.getType(), linkedJsonObject.getInteger("fieldType")) ||
                                    Objects.equals(FieldTypeEnum.STAR.getType(), linkedJsonObject.getInteger("fieldType"))) {
                                jsonExtract = XbbConstant.JSON_EXTRACT_DOUBLE;
                            } else if (Objects.equals(FieldTypeEnum.DATETIME.getType(), linkedJsonObject.getInteger("fieldType"))) {
                                jsonExtract = XbbConstant.JSON_EXTRACT_INT;
                            }*/
                            String formIdSuff = formIdTableMap.get(formId);
                            //String extractString = CommonHelper.getExtractString(jsonExtract, formIdSuff,attr);
                            //String extractString = formIdSuff + XbbConstant.POINT + attr;
                            //String extractString = attr;
                            if (!isSingle) {
                                //多表LinkedText是被修改过的字段，LinkedAttr里面的attr是原始字段
                                //extractString = CommonHelper.getExtractString(jsonExtract, formIdSuff,linkedJsonObject.getString("attr"));
                                //extractString = formIdSuff + XbbConstant.POINT + linkedJsonObject.getString("attr");
                                //extractString = linkedJsonObject.getString("attr");
                            }
                            //fieldsList.add(extractString + " AS " + attr);
                            fieldsList.add(formIdSuff + XbbConstant.POINT +attr);
                            if (StringUtils.isNotEmpty(formIdSuff)){
                                addSelectCol(formIdTableMap, selectItemsMap, formId, attr);
                            }
                        } else {
                            // //TODO  不在data内？   外层关联限制下应该都在data内
//                        fieldsList.add(s + " AS " + attr);
                        }
                    }
                } else if (FieldTypeEnum.BIRTHDAY.getType().equals(fieldAttrPojo.getFieldType())) {
                    //生日字段处理
                    String linkedText = fieldAttrPojo.getLinkedText();
                    //fieldsList.add(XbbConstant.JSON_EXTRACT_INT + "(" + formIdTableMap.get(fieldAttrPojo.getFormId()) + ".`data`,'" + linkedText + "')  AS " + linkedText);
                    fieldsList.add(formIdTableMap.get(fieldAttrPojo.getFormId()) + XbbConstant.POINT + linkedText +XbbConstant.AS + linkedText);
                    //fieldsList.add(linkedText);
                    addSelectCol(formIdTableMap, selectItemsMap, formId, linkedText);
                }

            }
        }
        //handleSummary(summaryAttrList, tableHead, parseAttrMap, summaryAttrMap, isSingle);
        //添加ID
        Map<Long, String> finalFormIdTableMap = formIdTableMap;
        selectItemsMap.keySet().forEach(key->{
            Set<String> valueSet = selectItemsMap.get(key);
            //valueSet.add(FieldTypeEnum.ID.getAlias());
            selectItemsMap.put(key,valueSet);
        });
        Pair<List<String>, HashMap<String, Set<String>>> listHashMapPair = new ImmutablePair<>(fieldsList, selectItemsMap);
        return listHashMapPair;
    }


    /**
     * 拼装表头
     *
     * @param chartEntity
     * @param isSingle
     * @param fieldsList
     * @param formIdTableMap
     * @param fieldAttrPojo
     * @param tableHead
     * @param parseAttrMap
     * @return boolean
     * @throws XbbException
     * @author xinpeng.jiang
     * @date 2021/11/22 13:36
     * @version 1.0*/
    public boolean handleHeadName(ChartEntity chartEntity, boolean isSingle, List<String> fieldsList, Map<Long, String> formIdTableMap,
                                  FieldAttrEntity fieldAttrPojo, JSONArray tableHead, Map<JSONObject,
            FieldAttrEntity> parseAttrMap, HashMap<String, Set<String>> selectItemsMap) {
        Integer fieldType = fieldAttrPojo.getFieldType();
        String attr = fieldAttrPojo.getAttr();
        JSONObject headName = new JSONObject();
        String label = fieldAttrPojo.getLabel();
        String labelName = fieldAttrPojo.getLabelName();
        String attrName = fieldAttrPojo.getAttrName();
        if (chartEntity != null) {
            if (Objects.equals(chartEntity.getChartType(), ChartTypeEnum.PK_CUSTOM.getCode())) {
                // 自定义pk
                headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, attrName);
            } else if (fieldAttrPojo.getAggType() != null) {
                // 查询表，汇总字段也会加到表头字段中，所以查询汇总方式
                AggTypeEnum aggTypeEnum = AggTypeEnum.getByAlias(fieldAttrPojo.getAggType());
                if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(), fieldType)) {
                    if (Objects.equals(labelName, label)) {
                        headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, attrName + XbbConstant.L_P + aggTypeEnum.getName() + XbbConstant.R_P);
                    } else {
                        headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, labelName + XbbConstant.L_P + aggTypeEnum.getName() + XbbConstant.R_P);
                    }
                } else {
                    if (Objects.equals(labelName, label)) {
                        String temp = Arrays.asList(label.split(StringConstant.DOUBLE_LINE)).get(0);
                        if (StringUtil.isNotEmpty(attrName)) {
                            temp = temp + StringConstant.DOUBLE_LINE + attrName;
                        }
                        headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, temp + XbbConstant.L_P + aggTypeEnum.getName() + XbbConstant.R_P);
                    } else {
                        headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, labelName + XbbConstant.L_P + aggTypeEnum.getName() + XbbConstant.R_P);
                    }
                }
            } else {
                if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(), fieldType)) {
                    if (Objects.equals(labelName, label)) {
                        String temp = Arrays.asList(label.split(StringConstant.DOUBLE_LINE)).get(0);
                        if (StringUtil.isNotEmpty(attrName)) {
                            temp = temp + StringConstant.DOUBLE_LINE + attrName;
                        }
                        headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, temp);
                    } else {
                        headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, labelName);
                    }
                } else {
                    if (Objects.equals(FieldTypeEnum.COMPUTED_FIELD.getType(), fieldType)) {
                        headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, Arrays.asList(label.split(StringConstant.DOUBLE_LINE)).get(0));
                    } else {
                        if (Objects.equals(labelName, label)) {
                            String temp = Arrays.asList(label.split(StringConstant.DOUBLE_LINE)).get(0);
                            if (StringUtil.isNotEmpty(attrName)) {
                                temp = temp + StringConstant.DOUBLE_LINE + attrName;
                            }
                            headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, temp);
                        } else {
                            headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, labelName);
                        }
                    }
                }
            }

        }else{
            if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(), fieldType) && chartEntity != null) {
                if (Objects.equals(labelName, label)) {
                    String temp = Arrays.asList(label.split(StringConstant.DOUBLE_LINE)).get(0);
                    if (StringUtil.isNotEmpty(attrName)) {
                        temp = temp + StringConstant.DOUBLE_LINE + attrName;
                    }
                    headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, temp);
                } else {
                    headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, labelName);
                }
            } else {
                if (Objects.equals(FieldTypeEnum.COMPUTED_FIELD.getType(), fieldType)  && chartEntity != null) {
                    headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, Arrays.asList(label.split(StringConstant.DOUBLE_LINE)).get(0));
                } else {
                    if (Objects.equals(labelName, label) && chartEntity != null) {
                        String temp = Arrays.asList(label.split(StringConstant.DOUBLE_LINE)).get(0);
                        if (StringUtil.isNotEmpty(attrName)) {
                            temp = temp + StringConstant.DOUBLE_LINE + attrName;
                        }
                        headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, temp);
                    } else {
                        if (Objects.nonNull(labelName)){
                            headName.put(StringConstant.SAAS_LINK_BUSINESS_NAME, labelName);
                        }
                    }
                }
            }
        }
        if (Objects.nonNull(headName) && Objects.nonNull(tableHead)){
            Long formId = fieldAttrPojo.getFormId();
            headName.put("frozeKey", formId + attr);
            headName.put("key", attr + XbbConstant.AMPERSAND + fieldAttrPojo.getFieldType());
            headName.put(StringConstant.FORM_ID, formId);
            headName.put("fieldType", fieldAttrPojo.getFieldType());
            //headName.put("columnFlag", fieldAttrPojo.getColumnFlag());
            headName.put("originAttr", fieldAttrPojo.getOriginalAttr());
            headName.put(StringConstant.ATTR, attr);
            if (fieldAttrPojo.getDateGroupType() != null) {
                headName.put("dateGroupType", fieldAttrPojo.getDateGroupType());
            }
            tableHead.add(headName);
            parseAttrMap.put(headName, fieldAttrPojo);
        }
        boolean specialFlag = specialTableTitleHandle(fieldAttrPojo, fieldsList, headName, isSingle, chartEntity, formIdTableMap,selectItemsMap);
        return specialFlag;
    }

    /**
     * 特殊字段 展示标题处理
     *
     * @param fieldAttrPojo 字段属性详情
     * @param fieldsList    展示字段
     * @param headName      回显标题属性值
     * @param isSingle      是否为单表
     * @param chartEntity   图表实体
     * @return
     * @author zhouwq
     * @date 2019/6/3 17:25
     */
    private  boolean specialTableTitleHandle(FieldAttrEntity fieldAttrPojo, List<String> fieldsList, JSONObject headName, Boolean isSingle,
                                                   ChartEntity chartEntity, Map<Long, String> formIdTableMap,HashMap<String, Set<String>> selectItemsMap) {
        boolean specialFlag = false;
        Integer fieldType = fieldAttrPojo.getFieldType();
        Integer businessType = fieldAttrPojo.getBusinessType();
        if (FieldTypeEnum.isSubFormType(fieldType)) {
            specialFlag = true;
            SubFormPoJo subFormPoJo = fieldAttrPojo.getSubForm();
            String str = JSONArray.toJSONString(subFormPoJo.getItems(), SerializerFeature.DisableCircularReferenceDetect);
            List<FieldAttrPojo> subFormAttrs = JSONArray.parseArray(str, FieldAttrPojo.class);
            List<JSONObject> subFormItems = new ArrayList<>();
            subFormAttrs.forEach(field -> {
                String attr = field.getAttr();
                JSONObject subFormObj = new JSONObject();
                String parentStr;
                String childStr;
                if (Objects.equals(fieldAttrPojo.getLabelName(), fieldAttrPojo.getLabel())) {
                    parentStr = fieldAttrPojo.getAttrName();
                } else {
                    parentStr = fieldAttrPojo.getLabelName();
                }
                if (Objects.equals(field.getLabelName(), field.getLabel())) {
                    childStr = field.getAttrName();
                } else {
                    childStr = field.getLabelName();
                }
                AggTypeEnum aggTypeEnum = AggTypeEnum.getByAlias(field.getAggType());
                if (Objects.isNull(field.getAggType())) {
                    subFormObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, parentStr + StringConstant.DOUBLE_LINE + childStr);
                } else {
                    subFormObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, parentStr + StringConstant.DOUBLE_LINE + childStr + XbbConstant.L_P + aggTypeEnum.getName() + XbbConstant.R_P);
                }
                subFormObj.put(StringConstant.KEY, attr + XbbConstant.AMPERSAND + field.getFieldType());
                subFormObj.put(StringConstant.FORM_ID, fieldAttrPojo.getFormId());
                subFormObj.put(FieldAttrConstant.FIELD_TYPE, field.getFieldType());
                subFormItems.add(subFormObj);
            });
            headName.put(StringConstant.ITEMS, subFormItems);
            String attr = fieldAttrPojo.getAttr();
            Long formId = fieldAttrPojo.getFormId();
            //fieldsList.add(JSON_EXTRACT_ARRAY_RAW + "(" + formIdTableMap.get(formId) + ".`data`,'" + attr + "')" + " AS " + attr);
            //fieldsList.add(formIdTableMap.get(formId) + XbbConstant.POINT + attr + XbbConstant.AS + attr);
            if (!SrFilterHandler.isNeedRelationSubFormTable(businessType,attr)){
                fieldsList.add(formIdTableMap.get(formId) + XbbConstant.POINT + attr + XbbConstant.AS + attr);
                addSelectCol(formIdTableMap, selectItemsMap, formId, attr);
            }else {
                //fieldsList.add("NUll"+ XbbConstant.AS + attr);
                //id-formid-businessType-saasMark-attr
                fieldsList.add(MessageFormat.format("{0}{1}{2}{3}{4}{5}\"{6}{7}{8}{9}{10}{11}{12}{13}\"){14}{15}", XbbConstant.CONCAT, XbbConstant.L_P, formIdTableMap.get(formId), StringConstant.POINT, FieldTypeEnum.ID.getAlias(), StringConstant.COMMA, XbbConstant.THE_CROSSED, formId.toString(), XbbConstant.THE_CROSSED, businessType.toString(), XbbConstant.THE_CROSSED, fieldAttrPojo.getSaasMark().toString(), XbbConstant.THE_CROSSED, attr, XbbConstant.AS, attr));
            }
        } else if (FieldTypeEnum.OWNERID.getType().equals(fieldType) || FieldTypeEnum.COUSERID.getType().equals(fieldType)) {
            specialFlag = true;
            //TODO
//            Long formId = fieldAttrPojo.getFormId();
            // 根据主表查到团队表
            String tableName = CommonHelper.getTeamNameByBusinessType(businessType);

            //int teamIdx = EsUtil.getTeamIdx(chartEntity, formId);
            //int teamIdx = getTeamIdx(null,formIdTableMap,formId);
            int teamIdx = 1;//todo
            if (FieldTypeEnum.OWNERID.getType().equals(fieldType)) {
                if (fieldsList != null) {
                    if (StringUtils.isEmpty(tableName)){//没有团队的表负责人处理
                        fieldsList.add(XbbConstant.OWNER_ID + XbbConstant.AS+XbbConstant.MY_TEAM_MAIN+ teamIdx);
                        return false;
                    }else {
                        fieldsList.add(tableName + XbbConstant.POINT + XbbConstant.TEAM_MAIN + XbbConstant.AS+XbbConstant.MY_TEAM_MAIN+ teamIdx);
                    }
                    //fieldsList.add(tableName + XbbConstant.POINT + XbbConstant.TEAM_MAIN + XbbConstant.AS+XbbConstant.OWNER_ID);
                }
            } else {
                if (StringUtil.isEmpty(tableName)) {
                    return false;
                }
                if (fieldsList != null) {
                    fieldsList.add(tableName + XbbConstant.POINT + XbbConstant.TEAM_CO + XbbConstant.AS+XbbConstant.MY_TEAM + teamIdx);
                }
            }

        }
        return specialFlag;
    }

    public static int getTeamIdx(ChartEntity chartEntity,Map<Long, String> formIdTableMap, Long formId) {
        if (Objects.nonNull(chartEntity)){
            JSONArray slaveSourcePojo = chartEntity.getSlaveSources();
            SlaveSourcePojo driverPojo = JSON.toJavaObject(chartEntity.getDriverSources(), SlaveSourcePojo.class);
            if (Objects.equals(driverPojo.getFormId(), formId)) {
                return 1;
            } else {
                List<SlaveSourcePojo> slaveSourceList = slaveSourcePojo.toJavaList(SlaveSourcePojo.class);
                for (int k = 0; k < slaveSourceList.size(); k++) {
                    SlaveSourcePojo sourcePojo = slaveSourceList.get(k);
                    if (Objects.equals(sourcePojo.getFormId(), formId)) {
                        return  k + 2;
                    }
                }
            }
        }else {
            int k = 0;
            for (Map.Entry entry : formIdTableMap.entrySet()) {
                k++;
                Object key = entry.getKey();
                if(Objects.equals(key,formId)){
                    return k;
                }
            }
        }
        return 1;
    }

    /**
     * 添加字段带别名
     *
     * @param isSingle
     * @param fieldsList      放在表头上的名字（分组字段也要放在表头返回）
     * @param groupFieldsList 分组字段
     * @param formIdTableMap
     * @param fieldAttrPojo
     * @param attr
     * @return
     */
    public HashMap<String, Set<String>> addFieldaliasList(HashMap<String, Set<String>> selectItemsMap, boolean isSingle, List<String> fieldsList,
                                                          List<String> groupFieldsList, Map<Long, String> formIdTableMap,
                                                          FieldAttrEntity fieldAttrPojo, String attr,
                                                          Map<String, String> sortMap, ChartEntity chartEntity) throws XbbException {
        //TODO 区分在colums和group BY的字段
        Integer fieldType = fieldAttrPojo.getFieldType();
        String sortAttr = null;
        Long formId = fieldAttrPojo.getFormId();
        if (Objects.nonNull(sortMap)){
            sortAttr = sortMap.get(attr);
        }
        /*if(isSingle){
            sortAttr = sortMap.get(attr);
        }else {
            sortAttr = sortMap.get(fieldAttrPojo.getOriginalAttr());
        }*/
        if (EsUtil.setInData(fieldType)) {
            //String jsonExtract = CommonHelper.getExtractFuntion(fieldType, null);
            if (BIHelp.isDateTimeByFieldType(fieldType)) {
                String originalAttr = attr;
                if (!isSingle) {
                    originalAttr = fieldAttrPojo.getOriginalAttr();
                }
                IntervalTypeEnum intervalTypeEnum = IntervalTypeEnum.getByFormatStr(fieldAttrPojo.getDateGroupType());
                //String s = XbbConstant.JSON_EXTRACT_INT + "(" + formIdTableMap.get(formId) + ".`data`,'" + originalAttr + "')";
                //String s = formIdTableMap.get(formId) + XbbConstant.POINT+  originalAttr;
                String s = originalAttr;
                if (Objects.isNull(formId)) {
                    //s = XbbConstant.JSON_EXTRACT_INT + "(" +"`data`,'" + originalAttr + "')";
                    s = "'" + originalAttr + "'";
                }
                String s2 = "";
                //注意下面这个没有写AS  别名，否则会造成相同别名数据格式的不一致
                if (groupFieldsList != null) {
                    String s1 = "";
                    if(Objects.equals(intervalTypeEnum.getDateFunctions(),IntervalTypeEnum.YEAR_QUARTER.getDateFunctions())){
                        s1 = "toInt64(toDateTime64(multiIf(formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Q')=='1', CONCAT(formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Y') ,'-01-01'),formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Q') =='2',CONCAT(formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Y') ,'-04-01'),formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Q')=='3', CONCAT(formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Y') ,'-07-01'),  CONCAT(formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Y') ,'-10-01')),0))";
                    }else if(Objects.equals(intervalTypeEnum.getDateFunctions(),IntervalTypeEnum.YEAR_WEEK.getDateFunctions())){
                        s1 = "toInt64(toDateTime64(formatDateTime(subtractDays(toDateTime64(" +
                                s +
                                ",0), toDayOfWeek(toDateTime64(" +
                                s +
                                ",0))-1), '" +
                                IntervalTypeEnum.YEAR_MONTH_DAY.getFormatPlaceholder() +
                                "'),0))";
                    }else {
                        s1 = "toInt64(toDateTime64(formatDateTime(toDateTime64(" +
                                s +
                                ",0), '" +
                                intervalTypeEnum.getFormatPlaceholder() +
                                "'),0))";
                    }
                    if (Objects.isNull(formId)) {
                        //s2 = "if(" + XbbConstant.JSON_HAS + "(" +  "`data`,'" + originalAttr + "')" + "," + s1 + ",null)";
                        s2 = originalAttr;
                    }else {
                        //s2 = "if(" + XbbConstant.JSON_HAS + "(" + formIdTableMap.get(formId) + ".`data`,'" + originalAttr + "')" + "," + s1 + ",null)";
                        //s2 = formIdTableMap.get(formId) + XbbConstant.POINT + originalAttr;
                        s2 = originalAttr;
                    }
                    groupFieldsList.add(s2);
                    if (StringUtil.isNotEmpty(sortAttr) && (Objects.equals(sortAttr.trim(), StringConstant.SORT_ASC_TAG) || Objects.equals(sortAttr.trim(), StringConstant.SORT_DESC_TAG))) {
                        sortMap.put(attr, s2 + " " + sortAttr);
                    }
                    fieldsList.add("MAX(" + s2 + ") AS " + attr);//todo
                } else {
                    if (StringUtil.isNotEmpty(sortAttr) && (Objects.equals(sortAttr.trim(), StringConstant.SORT_ASC_TAG) || Objects.equals(sortAttr.trim(), StringConstant.SORT_DESC_TAG))) {
                        sortMap.put(attr, s + "  " + sortAttr);
                    }
                    if (Objects.isNull(formId)) {
                        //s2 = "if(" + XbbConstant.JSON_HAS + "(" + "`data`,'" + originalAttr + "')" + "," + s + ",null)";
                        //s2 = originalAttr;
                    }else {
                        //s2 = "if(" + XbbConstant.JSON_HAS + "(" + formIdTableMap.get(formId) + ".`data`,'" + originalAttr + "')" + "," + s + ",null)";
                        //s2 = formIdTableMap.get(formId) + XbbConstant.POINT + originalAttr;
                    }
                    //fieldsList.add(s2 + " AS " + attr);
                    fieldsList.add(formIdTableMap.get(formId) + XbbConstant.POINT + originalAttr +XbbConstant.AS+originalAttr);
                    addSelectCol(formIdTableMap, selectItemsMap, formId, originalAttr);
                }
            } else if (Objects.equals(FieldTypeEnum.COMPUTED_FIELD.getType(), fieldType)) {
                //TODO
                //判断单表还是多表，拼script
                /*JSONObject formulaInfo = fieldAttrPojo.getFormulaInfo();
                String formula = formulaInfo.getString("formula");*/
                /*try {
                    formula = computedHelp.getString(formulaInfo, selectItemsMap, formula, formIdTableMap);
                    formulaInfo.put("formula", formula);
                    fieldAttrPojo.setFormulaInfo(formulaInfo);
                    fieldsList.add(formula + " AS " + attr);
                    // 排序
                    if (StringUtil.isNotEmpty(sortAttr) && (Objects.equals(sortAttr.trim(), "asc") || Objects.equals(sortAttr.trim(), "desc"))) {
                        sortMap.put(attr, attr + " " + sortAttr);
                    }
                } catch (XbbException e) {
                    log.error("计算字段的公式格式有问题", e);
                    throw e;
                }*/
            } else if ((Objects.equals(FieldTypeEnum.ADDRESS.getType(), fieldType) || Objects.equals(FieldTypeEnum.LOCATION.getType(), fieldType))) {
                //String s;
                String key = attr;
                if (!isSingle) {
                    key = fieldAttrPojo.getOriginalAttr();
                }
                if (attr.contains(".")) {
                    String[] keyArray = key.split("\\.");
                    /*s = JSON_EXTRACT_STRING +
                            "(" +
                            JSON_EXTRACT_RAW +
                            "(" + formIdTableMap.get(formId) +
                            ".`data`, '" +
                            keyArray[0] +
                            "'), '" +
                            keyArray[1] +
                            "')";*/
                    //s = "$"+XbbConstant.POINT+keyArray[0]+XbbConstant.POINT+keyArray[1];
                } else {
                    /*s =
                            JSON_EXTRACT_RAW +
                                    "(" + formIdTableMap.get(formId) +
                                    ".`data`, '" +
                                    key +
                                    "')";*/
                    //s = "$"+XbbConstant.POINT+key;
                }
                if (groupFieldsList != null) {
                    //String field = s + " AS `" + attr.replaceAll("\\.", "_") + "`";
                    String field = " `" + attr.replaceAll("\\.", "_") + "`";
                    fieldsList.add(field);
                    addSelectCol(formIdTableMap, selectItemsMap, formId, field);
                    groupFieldsList.add(field);
                } else {
                    boolean containsAddress = attr.contains(BusinessConstant.PROVINCE) || attr.contains(BusinessConstant.CITY) || attr.contains(BusinessConstant.DISTRICT);
                    //String field = s + XbbConstant.AS + attr;
                    String field = attr;
                    //兼容穿透查询
                    if (containsAddress) {
                        field = attr + " AS `" + attr.replaceAll("\\.", "_") + "`";
                        attr = "  `" + attr.replaceAll("\\.", "_") + "`";
                    }
                    fieldsList.add(formIdTableMap.get(formId) + XbbConstant.POINT + field +XbbConstant.AS+field);
                    addSelectCol(formIdTableMap, selectItemsMap, formId, attr);
                }
            } else {
                String tName = formIdTableMap.get(formId);
                //String dataInAttr = jsonExtract + "(" + tName + ".`data`,'" + attr + "')";
                //String dataInAttr = CommonHelper.getExtractString(jsonExtract,tName,attr);
                //String dataInAttr = tName + XbbConstant.POINT+ attr ;
                String dataInAttr = attr ;
                String attr_ori = attr ;
                if (!isSingle) {
                    // 多表取原attr
                    if (StringUtils.equals(XbbTableRefEnum.CONTRACT_PERFORMANCE.getTableName(), tName)) {
                        String originalAttr = fieldAttrPojo.getOriginalAttr();
                        dataInAttr = StringUtil.getDataBaseString(ContractPerformanceEnum.getRealAttr(originalAttr));
                        attr_ori = StringUtil.getDataBaseString(originalAttr);
                    }
                }
                String field = dataInAttr + XbbConstant.AS + attr_ori;
                fieldsList.add(formIdTableMap.get(formId) + XbbConstant.POINT + field);
                addSelectCol(formIdTableMap, selectItemsMap, formId, attr);
                if (groupFieldsList != null) {
                    groupFieldsList.add(field);
                }
                if (StringUtil.isNotEmpty(sortAttr) && (Objects.equals(sortAttr.trim(), StringConstant.SORT_ASC_TAG) || Objects.equals(sortAttr.trim(), StringConstant.SORT_DESC_TAG))) {
                    sortMap.put(attr, field + XbbConstant.SPACE + sortAttr);
                }
            }
        } else {
            String originalAttr = attr;
            if (!isSingle) {
                originalAttr = fieldAttrPojo.getOriginalAttr();
                //addSelectCol(formIdTableMap, selectItemsMap, formId, CommonHelper.generatargMax(StringUtil.getDataBaseString(originalAttr)));
                addSelectCol(formIdTableMap, selectItemsMap, formId, StringUtil.getDataBaseString(originalAttr));
            }
            if (BIHelp.isDateTimeByFieldType(fieldType)) {
                IntervalTypeEnum intervalTypeEnum = IntervalTypeEnum.getByFormatStr(fieldAttrPojo.getDateGroupType());
                String mode = "";
                if(Objects.equals(intervalTypeEnum.getDateFunctions(),IntervalTypeEnum.YEAR_WEEK.getDateFunctions())){
                    mode = "," + XbbConstant.MODE;
                }
                if (isSingle) {
                    //addSelectCol(formIdTableMap, selectItemsMap, formId, CommonHelper.generatargMax(StringUtil.getDataBaseString(originalAttr)));
                    addSelectCol(formIdTableMap, selectItemsMap, formId, StringUtil.getDataBaseString(originalAttr));
                }
                //注意下面这个没有写AS  别名，否则会造成相同别名数据格式的不一致
                if (groupFieldsList != null) {
                    //String s = formIdTableMap.get(formId) + "." + CommonHelper.renameUpdateTime(StringUtil.getDataBaseString(originalAttr));
                    //String s = formIdTableMap.get(formId) + "." + StringUtil.getDataBaseString(originalAttr);
                    String s = StringUtil.getDataBaseString(originalAttr);
                    String s1 = "";
                    if(Objects.equals(intervalTypeEnum.getDateFunctions(),IntervalTypeEnum.YEAR_QUARTER.getDateFunctions())){
                        s1 = "toInt64(toDateTime64(multiIf(formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Q')=='1', CONCAT(formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Y') ,'-01-01'),formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Q') =='2',CONCAT(formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Y') ,'-04-01'),formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Q')=='3', CONCAT(formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Y') ,'-07-01'),  CONCAT(formatDateTime(toDateTime64(" +
                                s +
                                ",0), '%Y') ,'-10-01')),0))";
                    }else if(Objects.equals(intervalTypeEnum.getDateFunctions(),IntervalTypeEnum.YEAR_WEEK.getDateFunctions())){
                        s1 = "toInt64(toDateTime64(formatDateTime(subtractDays(toDateTime64(" +
                                s +
                                ",0), toDayOfWeek(toDateTime64(" +
                                s +
                                ",0))-1), '" +
                                IntervalTypeEnum.YEAR_MONTH_DAY.getFormatPlaceholder() +
                                "'),0))";
                    }else {
                        s1 = "toInt64(toDateTime64(formatDateTime(toDateTime64(" +
                                s +
                                ",0), '" +
                                intervalTypeEnum.getFormatPlaceholder() +
                                "'),0))";
                    }
                    groupFieldsList.add(s1);
                    if (StringUtil.isNotEmpty(sortAttr) && (Objects.equals(sortAttr.trim(), StringConstant.SORT_ASC_TAG) || Objects.equals(sortAttr.trim(), StringConstant.SORT_DESC_TAG))) {
                        sortMap.put(attr, s1 + " " + sortAttr);
                    }
                    fieldsList.add(StringUtil.getDataBaseString(attr));
                    addSelectCol(formIdTableMap, selectItemsMap, formId, StringUtil.getDataBaseString(originalAttr));
                } else {
                    //fieldsList.add(formIdTableMap.get(formId) + "." + CommonHelper.renameUpdateTime(StringUtil.getDataBaseString(originalAttr)) + " AS " + StringUtil.getDataBaseString(attr));
                    //fieldsList.add(formIdTableMap.get(formId) + XbbConstant.POINT + StringUtil.getDataBaseString(originalAttr) + " AS " + StringUtil.getDataBaseString(attr));
                    String field = StringUtil.getDataBaseString(originalAttr);
                    fieldsList.add(formIdTableMap.get(formId) + XbbConstant.POINT + field +XbbConstant.AS+field);
                    addSelectCol(formIdTableMap, selectItemsMap, formId, field);
                    if (StringUtil.isNotEmpty(sortAttr) && (Objects.equals(sortAttr.trim(), "asc") || Objects.equals(sortAttr.trim(), "desc"))) {
                        //sortMap.put(attr, formIdTableMap.get(formId) + "." + CommonHelper.renameUpdateTime(StringUtil.getDataBaseString(originalAttr)) + " " + sortAttr);
                        //sortMap.put(attr, formIdTableMap.get(formId) + XbbConstant.POINT + StringUtil.getDataBaseString(originalAttr) + " " + sortAttr);
                        sortMap.put(attr, field + " " + sortAttr);
                    }
                }
            } else if (BIHelp.isTeamLogicByFieldType(fieldAttrPojo.getFieldType(), fieldAttrPojo.getBusinessType())) {
                String teamName = CommonHelper.getTeamNameByBusinessType(fieldAttrPojo.getBusinessType());
                String teamKey = null;
                String teamMain = XbbConstant.TEAM_MAIN;
                if (FieldTypeEnum.OWNERID.getType().equals(fieldAttrPojo.getFieldType())) {
                    teamKey = XbbConstant.MY_TEAM_MAIN;
                    teamMain = XbbConstant.TEAM_MAIN;
                } else if (FieldTypeEnum.COUSERID.getType().equals(fieldAttrPojo.getFieldType())) {
                    teamMain = XbbConstant.TEAM_CO;
                    teamKey = XbbConstant.MY_TEAM;
                }
                //int teamIdx = EsUtil.getTeamIdx(chartEntity, formId);
                int teamIdx = 1;
                String field = teamName + XbbConstant.POINT + teamMain + XbbConstant.AS + teamKey + teamIdx;
                fieldsList.add(field);
                if (groupFieldsList != null) {
                    groupFieldsList.add(field);
                }
                if (StringUtil.isNotEmpty(sortAttr) && (Objects.equals(sortAttr.trim(), "asc") || Objects.equals(sortAttr.trim(), "desc"))) {
                    sortMap.put(attr, field + " " + sortAttr);
                }
            } else {
                //String field = formIdTableMap.get(formId) + "." + CommonHelper.renameUpdateTime(StringUtil.getDataBaseString(originalAttr)) + " AS " + CommonHelper.renameUpdateTime(StringUtil.getDataBaseString(attr));
                //String field = formIdTableMap.get(formId) + "." + StringUtil.getDataBaseString(originalAttr) + " AS " + CommonHelper.renameUpdateTime(StringUtil.getDataBaseString(attr));
                //String field = formIdTableMap.get(formId) + "." + StringUtil.getDataBaseString(originalAttr) + " AS " + StringUtil.getDataBaseString(attr);
                String field = StringUtil.getDataBaseString(originalAttr);
                fieldsList.add(formIdTableMap.get(formId) + XbbConstant.POINT + field +XbbConstant.AS+field);
                addSelectCol(formIdTableMap, selectItemsMap, formId, field);
                if (groupFieldsList != null) {
                    groupFieldsList.add(field);
                }
                if (StringUtil.isNotEmpty(sortAttr) && (Objects.equals(sortAttr.trim(), StringConstant.SORT_ASC_TAG) || Objects.equals(sortAttr.trim(), StringConstant.SORT_DESC_TAG))) {
                    sortMap.put(attr, field + XbbConstant.SPACE + sortAttr);
                }
            }

        }
        return selectItemsMap;
    }


    /**
     * @return void
     * @throws
     * @Description 添加查询字段到map里
     * @Date 14:55 2021/12/22
     * @Param [formIdTableMap, selectItemsMap, formId, col]
     **/

    protected void addSelectCol(Map<Long, String> formIdTableMap, HashMap<String, Set<String>> selectItemsMap, Long formId, String col) {
        if (Objects.isNull(formIdTableMap) || Objects.isNull(selectItemsMap) || Objects.isNull(formId) || StringUtils.isEmpty(col)) {
            return;
        }
        String key = formIdTableMap.get(formId);
        Set<String> vSet = selectItemsMap.get(key);
        if (Objects.isNull(vSet)) {
            vSet = Sets.newHashSet();
        }
        vSet.add(col);
        selectItemsMap.put(key, vSet);
    }



    public  SqlBuilderHandler appendTeamJoin(SqlBuilderHandler startSqlBuilder, String selectItems, BaseDTO baseDTO,
                                             Pair<List<String>, HashMap<String, Set<String>>> listHashMapPair,
                                             ParamPojo paramPojo,Map<String,StringBuffer>  filterMap) throws XbbException {
        Pair<GroupSqlVO, HashMap<String, Set<String>>> mapPair = new ImmutablePair(new GroupSqlVO(),listHashMapPair.getValue());
        boolean isMaxPermission = CommonHelper.getIsMaxPermission(baseDTO);
        StringBuffer fields = new StringBuffer(selectItems);
        paramPojo.setCorpid(baseDTO.getCorpid());
        srTeamJoinHandler.tableJoin(mapPair,null, true, startSqlBuilder, fields, null,
                filterMap, 0, 10,null,isMaxPermission,false
        ,paramPojo);
        return startSqlBuilder;
    }
    /**
     * @author  gzt
     * @Description 相关产品、业绩分配select Items添加
     * @Date 9:33 2022/10/18
     * @param sTableName
     * @param itemStr
     * @return java.lang.String
     * @throws
     **/

    private String appendPrductItems(String sTableName, String itemStr) {
        String itemDate = "";
        if (Objects.equals(sTableName, XbbTableRefEnum.PURCHASE_PRODUCT.getTableName())) {
            String instockNum = StringUtil.getDataBaseString(RelatedProductConstant.INSTOCK_NUM);
            if (Objects.nonNull(itemStr) && !StringUtils.contains(itemStr,instockNum)) {
                if (StringUtils.isNotEmpty(itemDate)){
                    itemDate = itemDate + StringConstant.COMMA + instockNum +XbbConstant.SPACE;
                }else {
                    itemDate = instockNum +XbbConstant.SPACE;
                }
            }
            String outstockNum = StringUtil.getDataBaseString(RelatedProductConstant.OUTSTOCK_NUM);
            if (Objects.nonNull(itemStr) && !StringUtils.contains(itemStr,outstockNum)) {
                if (StringUtils.isNotEmpty(itemDate)){
                    itemDate = itemDate +XbbConstant.SPACE +StringConstant.COMMA + outstockNum +XbbConstant.SPACE;
                }else {
                    itemDate = outstockNum +XbbConstant.SPACE;
                }
            }
        }else if (Objects.equals(sTableName, XbbTableRefEnum.TRANSFER_PRODUCT.getTableName())) {
            String instockNum = StringUtil.getDataBaseString(RelatedProductConstant.INSTOCK_NUM);
            if (Objects.nonNull(itemStr) && !StringUtils.contains(itemStr,instockNum)) {
                if (StringUtils.isNotEmpty(itemDate)){
                    itemDate = itemDate + StringConstant.COMMA + instockNum +XbbConstant.SPACE;
                }else {
                    itemDate = instockNum +XbbConstant.SPACE;
                }
            }
        }else if (Objects.equals(sTableName, XbbTableRefEnum.PRODUCTION_ORDER_PRODUCT.getTableName())
                || Objects.equals(sTableName, XbbTableRefEnum.RETURNEDPURCHASE_PRODUCT.getTableName())) {
            String outstockNum = StringUtil.getDataBaseString(RelatedProductConstant.OUTSTOCK_NUM);
            if (Objects.nonNull(itemStr) && !StringUtils.contains(itemStr,outstockNum)) {
                if (StringUtils.isNotEmpty(itemDate)){
                    itemDate = itemDate + XbbConstant.SPACE +StringConstant.COMMA + outstockNum +XbbConstant.SPACE;
                }else {
                    itemDate = outstockNum +XbbConstant.SPACE;
                }
            }
        }
        return itemDate;
    }

    /**
     * @return java.lang.String
     * @throws
     * @Description
     * @Date 10:45 2021/12/22
     * @Param [itemMap, fields, itemStr, sTableName]
     **/

    public String getItemStr(HashMap<String, Set<String>> itemMap, String sTableName) {
        String itemStr = "";
        if (null != itemMap && StringUtils.isNotEmpty(sTableName) && itemMap.get(sTableName) != null) {
            itemStr = itemMap.get(sTableName).stream().collect(Collectors.joining(XbbConstant.SQL_COMMA));
        }
        String itemDate = appendPrductItems(sTableName, itemStr);
        if (StringUtils.isNotEmpty(itemDate)){
            itemStr = MessageFormat.format("{0}{1}{2}", itemStr, XbbConstant.SQL_COMMA, itemDate);

        }
        return itemStr;
    }


}
